# _*_coding:utf-8_*_
import time
from ATS.instrumentDriver import InstCom as inst
from ATS.datamanager.DataManager import DataManager


def analyzer_setup(sa, x):
    inst.write(sa, 'FREQ:CENT %s' % x)
    inst.write(sa, 'FREQ:TUNE:IMM')
    time.sleep(1)
    inst.write(sa, 'CALC:MARK2:MAX')
    inst.write(sa, 'CALC:MARK2:Y?')
    time.sleep(0.5)
    inst.write(sa, 'TRAC:DATA? TRACE1')
    time.sleep(1)
    str = inst.read(sa).split(',')
    buf = []
    buf.extend(str)
    return buf


def sg_setup(source, ssetup):
    freq, pow, rf_out = ssetup
    inst.write(source, ':RAD:ARB:WAV "WFM1:PULSE10US"')
    inst.write(source, ':RAD:ARB ON')
    inst.write(source, 'OUTP:MOD ON')  # MODULATION ON

    inst.write(source, 'FREQ %s' % freq)
    inst.write(source, 'POW %s' % pow)
    inst.write(source, 'OUTP %s' % rf_out)
    inst.write(source, 'OUTP:MOD ON')
    time.sleep(0.1)


def sa_powpeak(sa='SA1'):
    inst.write(sa, 'CALC:MARK2:MAX')
    inst.write(sa, 'CALC:MARK2:CPS ON')
    inst.write(sa, 'CALC:MARK2:Y?')
    time.sleep(0.1)
    mk2 = inst.read(sa)
    #    print 'peak=%s dBm' %mk2
    return mk2


def cal_sweep_pow(source='SS1', freq=3.6e9, start=-45, stop=-30):
    sa = 'SA1'
    ssetup = [freq, stop, 1]
    sg_setup(source, ssetup)

    inst.write(sa, 'CONF:SAN')
    inst.write(sa, 'FREQ:CENT %s' % freq)
    #    inst.write(sa,'FREQ:TUNE:IMM')
    inst.write(sa, 'FREQ:SPAN 1E8')
    inst.write(sa, 'SWE:TIME 50 ms')
    inst.write(sa, 'SWE:POIN 50001')
    #  50ms/5000 = 1us/point
    ref_level = start + 60
    inst.write(sa, 'DISP:WIND:TRAC:Y:RLEV %s' % ref_level)
    time.sleep(0.5)

    buf1 = []
    buf2 = []

    for j in range(start, stop + 1):
        buf1.append(j)
        ref_level += 1
        inst.write(sa, 'DISP:WIND:TRAC:Y:RLEV %s' % ref_level)

        ssetup = [freq, j, 1]
        str1 = "freq=%s, power=%s" % (freq, j)
        #        print str1
        sg_setup(source, ssetup)
        time.sleep(1)
        y = sa_powpeak(sa)
        buf2.append(float(y) - j)
        #        buf2.append(float(y))
        time.sleep(0.1)

    ssetup = [freq, start, 0]
    sg_setup(source, ssetup)  # RFout OFF

    str1 = ''
    str2 = ''
    for i in buf1:
        str1 = str1 + str(i) + ','
    for i in buf2:
        str2 = str2 + str(i) + ','

    filename = "cal_signal.txt"
    #    filename = os.path.join(constant.TEST_PATH,str2)
    with open(filename, 'w') as f:
        strlist = [str1, '\n', str2, '\n']
        f.writelines(strlist)


def find_1dbcomp(x_list, y_list):
    if len(y_list) < 10:
        return -100
    avg_gain = 0
    for i in range(5):
        avg_gain += y_list[i]
    avg_gain = avg_gain / 5
    for x, y in zip(x_list, y_list):
        print('x=', x, 'y=', y)
        if y < avg_gain - 1:
            print('1db compression is', x)
            return x


def am_sweep(source='SS1', freq=3.6e9, start=-45, stop=-30, cmin=-10, cmax=30, exgain=45, exloss=-25):
    sa = 'SA1'
    inst.write(sa, 'CONF:SAN')
    inst.write(sa, 'FREQ:CENT %s' % freq)
    #    inst.write(sa,'FREQ:TUNE:IMM')
    inst.write(sa, 'FREQ:SPAN 1E8')
    inst.write(sa, ':CORR:SA:GAIN %s' % exloss)
    inst.write(sa, 'SWE:TIME 50 ms')
    inst.write(sa, 'SWE:POIN 50001')
    #  50ms/5000 = 1us/point
    ref_level = start + exgain + 20
    inst.write(sa, 'DISP:WIND:TRAC:Y:RLEV %s' % ref_level)
    time.sleep(1)

    ssetup = [freq, stop, 1]
    sg_setup(source, ssetup)

    buf1 = []
    buf2 = []

    for j in range(start, stop + 1):
        buf1.append(j + exgain)
        ref_level += 1
        inst.write(sa, 'DISP:WIND:TRAC:Y:RLEV %s' % ref_level)

        ssetup = [freq, j, 1]
        str1 = "freq=%s, power=%s" % (freq, j)
        #        print str1
        sg_setup(source, ssetup)
        time.sleep(1.2)
        y = sa_powpeak(sa)
        time.sleep(0.1)
        if y:
            buf2.append(float(y) - j - exgain)
        #        buf2.append(float(y))
        time.sleep(0.1)

    ssetup = [freq, start, 0]
    sg_setup(source, ssetup)  # RFout OFF

    x1 = find_1dbcomp(buf1, buf2)
    if x1 < -50:
        z = 0
    elif cmin < x1 < cmax:
        z = 1
    else:
        z = 0
    result = [str(x1)]

    DataManager().postarraydata('In_Amp', buf1)
    DataManager().postarraydata('Out_Amp', buf2)
    DataManager().postarraydata('Comp_1dB', result)
    DataManager().postarraydata('Pass_Fail', str(z))
